const fs = require("fs");
const path = require("path");
const os = require("os");
const packageJson = require("../package.json");
const version = packageJson.version;

const _debug = function (message) {
  console.log(`[dotenv]${version}[DEBUG] ${message}`);
};

const parse = function parse(src) {
  const obj = {};

  src
    .toString()
    .split("\n")
    .forEach((item) => {
      const keyValueArr = item.split("=");
      const key = keyValueArr[0];
      const val = keyValueArr[1] || "";
      obj[key] = val;
    });

  return obj;
};

const resolveHome = (envPath) => {
  return envPath[0] === "~"
    ? path.join(os.homedir(), envPath.slice(1))
    : envPath;
};

const configDotenv = function (options) {
  let dotenvPath = path.resolve(process.cwd(), ".env");
  let encoding = "utf8";
  let debug = Boolean(options && options.debug);

  if (options.encoding) {
    encoding = options.encoding;
  } else {
    if (debug) {
      _debug("No encoding is specified. UTF-8 is used by default");
    }
  }

  let optionPaths = [dotenvPath];
  console.log("options.path", options.path);
  if (options.path) {
    if (!Array.isArray(options.path)) {
      optionPaths = [resolveHome(options.path)];
    } else {
      optionPaths = [];
      options.path.forEach((path) => {
        optionPaths.push(resolveHome(path));
      });
    }
  }
  console.log("optionPaths==", optionPaths);

  const parseAll = {};
  for (const path of optionPaths) {
    const envContent = parse(fs.readFileSync(path, encoding), { debug });
    populate(parseAll, envContent, options);
  }

  let processEnv = process.env;

  populate(processEnv, parseAll, options);
  return parseAll;
};

const populate = function (processEnv, parsed, options) {
  Object.keys(parsed).forEach((key) => {
    if (Object.prototype.hasOwnProperty.call(processEnv, key)) {
      if (options.override) {
        processEnv[key] = parsed[key];
      }
      if (options.debug) {
        if (options.override) {
          _debug(`${key} is already defined in process.env`);
          _debug("but it is overridden because override is true");
        } else {
          _debug(`${key} is already defined in process.env`);
          _debug("but it is not overridden because override is false");
        }
      }
    } else {
      processEnv[key] = parsed[key];
    }
  });
};

const config2 = function (options) {
  console.log("os==", os.homedir());
  let envPath = path.resolve(process.cwd(), ".env");

  let encoding = "utf8";

  let debug = false;
  if (options) {
    if (options.path !== null) {
      envPath = resolveHome(options.path);
    }
    if (options.encoding !== null) {
      encoding = options.encoding;
    }

    if (options.debug !== null) {
      debug = true;
    }
  }

  const envContent = parse(fs.readFileSync(envPath, encoding), { debug });

  Object.keys(envContent).forEach((key) => {
    if (!Object.prototype.hasOwnProperty.call(process.env, key)) {
      process.env[key] = envContent[key];
    }
  });
  //   console.log(process.env);
  return envContent;
};

const envConfig = configDotenv({
  path: [
    "~/zhen/work/study-demo/dotenv/examples2/.env",
    "~/zhen/work/study-demo/dotenv/examples/.env",
  ],
  debug: true,
});

console.log(envConfig);
